package com.hemaapp.yjnh.activity;

import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.Manifest;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.utils.PermissionUtils;
import com.hemaapp.yjnh.view.MoneyEditText;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import xtom.frame.util.XtomToastUtil;

/**
 * 手动转账和扫码转增粮票
 * 粮票转增
 */
public class TransferActivity extends BaseActivity implements OnClickListener {

    private static final int REQUEST_CONTACT = 0x103;//系统通讯录
    private static final int PERMISSION_READ_CONTACTS = 0x104;//读取系统通讯录权限

    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.edt_accout)
    EditText edtAccout;
    @Bind(R.id.iv_contact)
    ImageView ivContact;
    @Bind(R.id.edt_money)
    MoneyEditText edtMoney;
    @Bind(R.id.tv_hint)
    TextView tvHint;

    private String keytype = "";//1通过扫码转给平台;2通过扫码转给商家;3通过扫码转给个人
    private String accout = "";//接收方的账户
    private String name = "";
    private String money;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_zhuanzeng);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        accout = mIntent.getStringExtra("accout");
        keytype = mIntent.getStringExtra("keytype");
    }

    @Override
    protected void setListener() {
        titleText.setText("转赠");
        titleRightBtn.setVisibility(View.GONE);
        edtMoney.setAfterDotLength(0);
        if (!isNull(accout)) {
            edtAccout.setText(accout);
            edtAccout.setSelection(accout.length());
            tvHint.setVisibility(View.GONE);
            ivContact.setClickable(false);
        }
    }

    @OnClick({R.id.title_left_btn, R.id.iv_contact, R.id.btn_ok})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.iv_contact:
                if(ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED
                        || ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
//                    if (ActivityCompat.shouldShowRequestPermissionRationale(mContext, android.Manifest.permission.READ_CONTACTS)) {
//                        //已经禁止提示了
//                        XtomToastUtil.showShortToast(mContext, "您已禁止该权限，需要重新开启");
//                    } else {
                        ActivityCompat.requestPermissions(mContext,
                                new String[]{android.Manifest.permission.READ_CONTACTS},
                                PERMISSION_READ_CONTACTS);
//                    }
                }else {
                    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    startActivityForResult(intent, REQUEST_CONTACT);
                }
                //2017.01.16 判断6.0 权限
//                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
//                startActivityForResult(intent, REQUEST_CONTACT);
                break;
            case R.id.btn_ok:
                accout = edtAccout.getText().toString().trim();
                money = edtMoney.getText().toString();
                if (isNull(accout)) {
                    XtomToastUtil.showShortToast(mContext, "请输入对方账户");
                    break;
                }
                User user = getApplicationContext().getUser();
                if (!isNull(user.getUsername()) && user.getUsername().equals(accout)) {
                    XtomToastUtil.showShortToast(mContext, "不能转赠给自己!");
                    break;
                }
                if (money.isEmpty()) {
                    XtomToastUtil.showShortToast(mContext, "请输入转赠金额");
                    break;
                }
                if (money.equals("0")) {
                    XtomToastUtil.showShortToast(mContext, "转增金额不能为0");
                    break;
                }
                getNetWorker().couponConvert(getApplicationContext().getUser().getToken(),
                        accout, name, money, keytype);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK != resultCode) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CONTACT:
                Uri contactData = data.getData();
                Cursor cursor = managedQuery(contactData, null, null, null,
                        null);
                cursor.moveToFirst();
                try {
                    accout = this.getContactPhone(cursor);
                    accout = accout.replace(" ", "");
                    edtAccout.setText(accout);
                    edtAccout.setSelection(accout.length());
                }catch (Exception e) {
                    e.printStackTrace();
                    XtomToastUtil.showShortToast(mContext, "请确认打开读取联系人权限");
                    PermissionUtils.gotoMiuiPermission(mContext);
                }
                if(Build.VERSION.SDK_INT < 14) {//14版本以上会自动关闭cursor，如果手动关闭会报错
                    cursor.close();
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_READ_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, REQUEST_CONTACT);
            } else {
                XtomToastUtil.showShortToast(mContext, "请打开通讯录权限");
            }
        }
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case SCORE_SAVEOPERATOR:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case SCORE_SAVEOPERATOR:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case SCORE_SAVEOPERATOR:
                XtomToastUtil.showShortToast(mContext, "转赠成功");
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.UPDATE_INFO);
                EventBus.getDefault().post(msg);
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case SCORE_SAVEOPERATOR:
                XtomToastUtil.showShortToast(mContext, "转增失败" + baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case SCORE_SAVEOPERATOR:
                XtomToastUtil.showShortToast(mContext, "转增失败,请稍后再试");
                break;
        }
    }

    private String getContactPhone(Cursor cursor) {
        int phoneColumn = cursor
                .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
        int phoneNum = cursor.getInt(phoneColumn);
        String result = "";
        if (phoneNum > 0) {
            // 获得联系人的ID号
            int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            String contactId = cursor.getString(idColumn);
            // 获得联系人电话的cursor
            Cursor phone = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
                            + contactId, null, null);
            if (phone.moveToFirst()) {
                for (; !phone.isAfterLast(); phone.moveToNext()) {
                    int index = phone
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    int typeindex = phone
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
                    int phone_type = phone.getInt(typeindex);
                    String phoneNumber = phone.getString(index);
                    result = phoneNumber;
//                  switch (phone_type) {//此处请看下方注释
//                  case 2:
//                      result = phoneNumber;
//                      break;
//
//                  default:
//                      break;
//                  }
                }
                if (!phone.isClosed()) {
                    phone.close();
                }
            } else {
                showTextDialog("读取手机通讯录失败！");
            }
        }
        return result;
    }
}
